package com.atguigu.smsservice.controller;

import com.atguigu.commonutils.Result;
import com.atguigu.smsservice.service.SmsService;
import com.atguigu.smsservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author zr
 */
@RestController
//@CrossOrigin
@Api(tags = "短信管理")
@RequestMapping("/api/sms")
public class SmsApiController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{phone}")
    public Result send(
            @ApiParam(name = "phone", value = "手机号", required = true)
            @PathVariable String phone) {
        // 从redis中获取验证码 如果能获取到数据就直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok().message("短信发送成功");
        }
        // 如果从redis中取不到 就从腾讯云发送
        // 生成随机数 传递腾讯云进行发送
        code = RandomUtil.getSixBitRandom();
        // 调用service发送短信的方法
        boolean flag = smsService.send(phone, code);
        if (!flag) {
            return Result.fail().message("短信发送失败");

        }
        // 发送成功 将验证码放到redis中 设置有效时间
        redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
       return Result.ok().message("短信发送成功");
    }
}
